<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

</body>
<script>
  function myReduce(arr, fn, initValue) {
    // var arr = [9,1,7,3,4,6,8,2,5];
    // var fn = function(prev,item,index,array){
    //     return prev + item;   // 0 + 9
    // }
    // var initValue = 0;

    var brr = [];

    if (initValue != undefined) {// 有初始值
      var sum = initValue;
      for (var i = 0; i < arr.length; i++) {
        var item = arr[i];  //循环的当前元素
        var index = i;    // 循环的当前下标
        var array = arr;  //原数组
        sum = fn(sum, item, index, array); // 实际参数 (函数调用时实际传入的值)
      }
    } else {  // 如果没有初始值
      var sum = arr[0];   //默认数组的第一个值作为prev的初始值,从第二个元素开始遍历
      for (var i = 1; i < arr.length; i++) {
        var item = arr[i];  //循环的当前元素
        var index = i;    // 循环的当前下标
        var array = arr;  //原数组
        sum = fn(sum, item, index, array); // 实际参数 (函数调用时实际传入的值)
      }
    }
    return sum;
  }

  var list = [9, 1, 7, 3, 4, 6, 8, 2, 5];
  console.log("原数组", list);
  // var res =  myReduce([9,1,7,3,4,6,8,2,5],function(prev,item,index,array){
  //     return prev + item;
  // },0)
  var res = myReduce([9, 1, 7, 3, 4, 6, 8, 2, 5], function (prev, item, index, array) {
    console.log(prev, item, index);
    return prev + item;
  })
  console.log(res);


</script>

</html>